<template>
  <div v-loading="loading">
    <el-card>
      <el-form
        :model="payApplyForm"
        :inline="true"
        ref="payApplyFormRef"
        :rules="rules"
        label-width="auto"
        size="mini"
      >
        <!--基本用户信息-->
        <el-row>
          <el-form-item label="申请单号">
            {{initData.applyNo}}
            <el-tooltip effect="light" placement="bottom">
              <div slot="content">
                <div
                  v-html="approveProgressHtmlStr"
                  style="max-width:500px;overflow:auto;background: #e1e5e8;font-size: 15px;line-height: 16px;color: #888;max-height: 320px;"
                ></div>
              </div>
              <i
                style="font-size:20px"
                class="el-icon-s-flag"
              ></i>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="申请人" style="margin-left: 50px">
            {{initData.applyUserName}}
          </el-form-item>
          <el-form-item label="申请时间" style="margin-left: 50px">
            {{initData.applyTime}}
          </el-form-item>
          <el-form-item label="申请部门" style="margin-left: 50px">
            {{initData.applyDeptName}}
          </el-form-item>
          <el-form-item prop="feeBelongDeptId" label="费用中心" style="margin-left: 90px">
            <el-select
              v-model="payApplyForm.feeBelongDeptId"
              filterable
              clearable
              placeholder="请选择"
              :disabled="editDisabled"
            >
              <el-option
                v-for="(item, key) in initData.deptMap"
                :key="key"
                :label="item"
                :value="parseInt(key)">
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <!--第二行-->
        <el-row :gutter="10">
          <!--第一列-->
          <el-col :span="6">
            <el-form-item prop="serveCompanyId" label="公司简称">
              <el-select
                v-model="payApplyForm.serveCompanyId"
                :remote-method="searchServeCompany"
                placeholder="请输入至少两个关键字"
                clearable
                filterable
                remote
                :disabled="serveCompanySelectDisabled"
                @change="queryServeCompanyAccount"
              >
                <el-option
                  v-for="(item, key) in serveCompanyMap"
                  :key="key"
                  :label="item"
                  :value="parseInt(key)">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="applyAmt" label="申请金额">
              <el-input-number v-model="payApplyForm.applyAmt" :min="0" :controls="false" :precision="2" style="width: 190px" :disabled="editDisabled"></el-input-number>
            </el-form-item>
            <el-form-item prop="currencyType" label="币种">
              <el-select
                v-model="payApplyForm.currencyType"
                filterable
                :disabled="editDisabled"
              >
                <el-option
                  v-for="(item, key) in initData.currencyMap"
                  :key="item"
                  :label="key"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="payType" label="支付方式">
              <el-select
                v-model="payApplyForm.payType"
                placeholder="请选择"
                :disabled="editDisabled"
              >
                <el-option
                  v-for="item in payTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="payDate" label="支付日期">
              <el-date-picker
                v-model="payApplyForm.payDate"
                type="date"
                value-format="yyyy-MM-dd"
                :disabled="editDisabled"
                style="width: 190px"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="付款账号">
              <el-select
                v-model="payApplyForm.companyBankId"
                filterable
                clearable
                placeholder="请选择"
                :disabled="editDisabled"
              >
                <el-option
                  v-for="(item, key) in initData.companyBankMap"
                  :key="key"
                  :label="item"
                  :value="parseInt(key)">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="总销账金额">
              <el-input-number v-model="payApplyForm.totalOffAmount" :min="0" :controls="false" :precision="2" style="width: 190px" :disabled="editDisabled"></el-input-number>
            </el-form-item>
            <el-form-item label="待支付余额">
              <el-input-number v-model="payApplyForm.toPayAmt" :min="0" :controls="false" :precision="2" style="width: 190px" :disabled="editDisabled"></el-input-number>
            </el-form-item>
          </el-col>
          <!--第二列-->
          <el-col :span="10">
            <el-form-item prop="applyRemark" label="申请说明">
              <el-input type="textarea" v-model="payApplyForm.applyRemark" placeholder="请输入" style="width: 600px" :disabled="editDisabled"></el-input>
            </el-form-item>
            <el-form-item prop="serveCompanyAccountId" label="收款账户">
              <el-select
                v-model="payApplyForm.serveCompanyAccountId"
                filterable
                clearable
                style="width: 600px"
                :disabled="editDisabled"
              >
                <el-option
                  v-for="(item, index) in serveCompanyAccountList"
                  :key="item.id"
                  :label="item.accountShowName"
                  :value="parseInt(item.id)">
                </el-option>
              </el-select>
            </el-form-item>
            <div class="margin-bottom flex justify-start">
              <span class="my_color" @click="selectRate">汇率： </span>
              <div class="my_left">
                <p
                  id="offAccountCurrencyRate"
                  class="margin-bottom-sm"
                  v-for="(v, i) in offAccountCurrencyRate"
                  :key="i"
                >
                  {{ offAccountCurrencyRate[i] }}
                </p>
              </div>
            </div>
            <el-row>
              <el-col :span="24">
                <el-form-item label="总计：">
                  <div class="text-sm" v-show="isShow">
                    <p class="text-bold">{{ totalOffResult }}</p>
                    <p class="margin-0" v-show="totalWriteOffTitle">
                      销账总计：
                    </p>
                    <p class="margin-0" v-for="(v, i) in offCurrencyMap" :key="i">
                      {{ i }} ：{{ offCurrencyMap[i] }}
                    </p>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="手续费">
                  <el-input-number v-model="payApplyForm.serviceCharge" :min="0" :controls="false" :precision="2" :disabled="editDisabled"></el-input-number>
                </el-form-item>
                <el-form-item label="币种" style="margin-left: -20px">
                  <el-select
                    v-model="payApplyForm.serviceChargeCurrencyType"
                    filterable
                    style="width: 100px"
                    :disabled="editDisabled"
                  >
                    <el-option
                      v-for="(item, key) in initData.currencyMap"
                      :key="item"
                      :label="key"
                      :value="item">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-button type="primary" size="small" @click="genServiceCharge" :disabled="editDisabled">生成费用</el-button>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="电讯费">
                  <el-input-number v-model="payApplyForm.telecomCharge" :min="0" :controls="false" :precision="2" :disabled="editDisabled"></el-input-number>
                </el-form-item>
                <el-form-item label="币种" style="margin-left: -20px">
                  <el-select
                    v-model="payApplyForm.telecomChargeCurrencyType"
                    filterable
                    style="width: 100px"
                    :disabled="editDisabled"
                  >
                    <el-option
                      v-for="(item, key) in initData.currencyMap"
                      :key="item"
                      :label="key"
                      :value="item">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-button type="primary" size="small" @click="genTelecomCharge" :disabled="editDisabled">生成费用</el-button>
              </el-col>
            </el-row>
          </el-col>
          <!--附件上传-->
          <el-col :span="7">
            <el-form-item label="附件" required="true">
              <el-upload
                class="upload-demo"
                drag
                :http-request="fileUpload"
                multiple
                :show-file-list="false"
                :disabled="editDisabled"
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              </el-upload>
            </el-form-item>
            <el-table
              :data="fileTableData"
              >
              <el-table-column
                prop="fileName"
                label="文件名"
                width="300">
              </el-table-column>
              <el-table-column
                prop="fileSize"
                label="文件大小"
                width="100">
              </el-table-column>
              <el-table-column
                prop="fileType"
                label="文件类型">
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-tooltip content="下载">
                    <i
                      style="color:#57dfecfa;"
                      class="el-icon-download pointer margin-right-sm text-xl"
                      @click="fileDownload(scope.$index, scope.row)"
                    ></i>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>

        <div class="flex justify-end margin-top">
          <el-button-group>
            <el-button type="primary" size="small" @click="save" :disabled="editDisabled">保存</el-button>
            <el-button type="primary" size="small" @click="submitForm('payApplyFormRef')" :disabled="editDisabled">提交</el-button>
          </el-button-group>
        </div>
      </el-form>
    </el-card>

    <!-- 弹框：选择销账汇率 -->
    <el-dialog title="请选择销账汇率" :visible.sync="dialogTableVisible">
      <div style="height:550px;" class="scrollbar">
        <el-scrollbar style="height:100%">
          <el-table :data="writeoffData" ref="accountTable" class="text-sm">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column
              prop="sourceCurrency"
              label="原始转换币种"
            ></el-table-column>
            <el-table-column
              prop="targetCurrency"
              label="目标转换币种"
            ></el-table-column>
            <el-table-column prop="rate" label="转换币率">
              <template slot-scope="scope">
                <div @dblclick="showInput">
                  <span v-if="showRate">{{ scope.row.rate }}</span>
                  <el-input
                    v-if="showInputRate"
                    size="mini"
                    clearable
                    v-model="scope.row.rate"
                  ></el-input>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="operator" label="运算符">
              <template slot-scope="scope">
                <span v-if="scope.row.operator == 1">乘</span>
                <span v-if="scope.row.operator == 2">除</span>
              </template>
            </el-table-column>
          </el-table>
        </el-scrollbar>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTableVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="saveRate" size="small">确 定</el-button>
      </div>
    </el-dialog>

    <!--搜索框-->
    <el-card>
      <el-form
        :model="searchForm"
        :inline="true"
        size="mini"
        class="padding-top-sm"
        label-position="left"
        label-width="90px"
      >
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="录入人">
              <el-select
                v-model="searchForm.inputUser"
                filterable
                clearable
                placeholder="请选择"
                style="width: 190px"
              >
                <el-option
                  v-for="(item, value) in initData.userMap"
                  :key="value"
                  :label="item"
                  :value="parseInt(value)"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="应收应付备注">
              <el-input v-model="searchForm.receivePayRemark" placeholder="请输入" style="width: 190px"></el-input>
            </el-form-item>

            <el-form-item prop="accountDate" label="费用时间">
              <el-date-picker
                v-model="searchForm.accountDate"
                unlink-panels
                type="daterange"
                style="width: 190px"
                start-placeholde="开始时间"
                end-placeholde="结算时间"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>

            <el-form-item label="费用类型">
              <el-select
                v-model="searchForm.costType"
                style="width: 190px"
              >
                <el-option
                  v-for="item in costTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="销售">
              <el-select
                v-model="searchForm.salesManId"
                filterable
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="(item, value) in initData.userMap"
                  :key="value"
                  :label="item"
                  :value="parseInt(value)"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="费用名称">
              <el-select
                v-model="searchForm.costNames"
                filterable
                clearable
                multiple
                placeholder="请选择"
              >
                <el-option
                  v-for="(item, value) in initData.costNamesMap"
                  :key="value"
                  :label="item"
                  :value="parseInt(value)"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="币种">
              <el-select
                v-model="searchForm.currency"
                filterable
              >
                <el-option
                  v-for="(item, key) in initData.currencyMap"
                  :key="item"
                  :label="key"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="运单号">
              <el-input type="textarea" v-model="searchForm.waybillNos" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="参考号">
              <el-input type="textarea" v-model="searchForm.referenceNos" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="M单号">
              <el-input type="textarea" v-model="searchForm.masterNumbers" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="追踪号">
              <el-input type="textarea" v-model="searchForm.trackNumbers" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="flex justify-end margin-top">
          <el-button-group>
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-search"
              @click="queryFinanceReceiveDetails"
              :disabled="editDisabled"
            >查询</el-button>
            <el-button type="primary" size="mini" @click="amountTotal" :disabled="editDisabled">总计</el-button>
            <el-button type="primary" size="mini" @click="exportTableData" :disabled="editDisabled">导出</el-button>
          </el-button-group>
        </div>
      </el-form>
    </el-card>

    <!--销账明细table-->
    <el-card>
      <el-table size="mini" :data="tableData" class="text-sm" id="out-eltable">
        <el-table-column type="index" label="序号"/>
        <el-table-column
          prop="waybillNo"
          label="运单号"
          sortable
          width="100"
        >
        </el-table-column>
        <el-table-column
          prop="referenceNo"
          label="参考号"
          sortable
          width="100">
        </el-table-column>
        <el-table-column
          prop="masterNumber"
          sortable
          label="M单号">
        </el-table-column>
        <el-table-column
          prop="inStockTime"
          label="入库日期"
          sortable
        >
        </el-table-column>

        <el-table-column label="费用名称" prop="costNameId" sortable>
          <template slot-scope="scope">
            {{ initData.costNamesMap[scope.row["costNameId"]] }}
          </template>
        </el-table-column>

        <el-table-column
          prop="remain"
          label="余额">
        </el-table-column>

        <el-table-column
          prop="currency"
          label="币种"
          sortable>
        </el-table-column>

        <!--销账金额-->
        <el-table-column prop="offMoney">
          <template slot="header" slot-scope="scope">
            <span>销账金额</span>
            <span class="my_color" @click="selectAll">{{texts ? "全选" : "全不选"}}</span>
          </template>
          <template slot-scope="scope">
            <el-input
              size="mini"
              v-model="scope.row.offMoney"
              @focus="onFocus($event, scope)"
              style="width:120px"
              clearable
            ></el-input>
            <span v-show="false">{{ scope.row.offMoney }}</span>
          </template>
        </el-table-column>

        <el-table-column
          prop="accountDate"
          label="费用日期"
          sortable
        >
        </el-table-column>
        <el-table-column
          prop="remark"
          label="备注信息">
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
  import { ajax } from "@/store/yg/common/utils";
  import { untransform } from "@/store/yg/common/uri";
  import { m } from "@/store/yg/common/local";
  import { clone } from "@/utils/clone";
  import { parseTime } from "@/utils";
  import FileSaver from "file-saver";
  import XLSX from "xlsx";
  import axios from "axios";
  import * as constant from "@/store/yg/common/constant";

  export default {
    data() {
      return {
        editDisabled: false,
        approveProgressHtmlStr: '',
        payApplyForm: {
          currencyType: 'RMB'
        },
        serveCompanySelectDisabled: false,
        serveCompanyAccountList: null,//服务商收款账户
        action: "",
        loading: false,
        isShow: false,//总计区域内容显示
        texts: true,
        totalOffResult: "",
        totalDataNum: null, //总计金额
        totalWriteOffTitle: false, //销账总计文字显示
        offCurrencyMap: {},
        selectData: [], //选中的汇率数据
        serveCompanyMap: [],
        initData: {},
        payTypeOptions: [
        {
          value: 1,
          label: '银行卡'
        }, {
          value: 2,
          label: '电汇'
        }],
        costTypeOptions: [
        {
          value: 0,
          label: 'FBA费用'
        }, {
          value: 1,
          label: '海外仓费用'
        }],
        writeoffData: [], // 记账汇率
        offAccountCurrencyRate: [],//汇率(JPY*RMB=1:0.07)
        dialogTableVisible: false,
        showRate: true,
        showInputRate: false,
        rules: {
          feeBelongDeptId: [{
            required: true,
            message: '请选择',
            trigger: 'blur'
          }],
          applyRemark: [{
            required: true,
            message: '请选择',
            trigger: 'blur'
          }],
          serveCompanyAccountId: [{
            required: true,
            message: '请选择',
            trigger: 'blur'
          }],
          serveCompanyId: [{
            required: true,
            message: '请选择',
            trigger: 'blur'
          }],
          applyAmt: [{
            required: true,
            message: '请选择',
            trigger: 'blur'
          }],
          currencyType: [{
            required: true,
            message: '请选择',
            trigger: 'blur'
          }],
          payType: [{
            required: true,
            message: '请选择',
            trigger: 'blur'
          }],
          payDate: [{
            required: true,
            message: '请输入',
            trigger: 'blur'
          }]
        },
        fileTableData: [],
        tableData: [],//销账明细表格数据
        checkCurrencyResult: true,
        searchForm: {
          costType: 0
        },
      };
    },

    created: function() {
      this.action =
        constant.API_SERVER +
        "/api/consume/upload?uri=" +
        untransform(this.$route.params.uri) +
        "&f=fileUpload&type=blank&name=sub&id=" +
        this.$store.state.edit.id;
    },

    mounted() {
      if (this.$route.query.pid) {
        this.edit();
      } else {
        this.init();
      }
    },

    methods: {

      async edit() {
        let payApplyId = this.$route.query.pid;
        let payApplyReq = {};
        payApplyReq.id = payApplyId;
        //请求后台
        const { code, data, message } = await ajax("edit", {
          payApply: payApplyReq
        });
        if (code !== 200) {
          if (message) {
            this.$message.error(message);
          } else {
            this.$message.error("服务器异常");
          }
          return;
        }
        //是否可编辑
        this.editDisabled = data.editDisabled;

        //页面顶部的基本用户信息
        this.initData.applyNo = data.financePayApply.applyNo;
        this.initData.applyUserName = data.applyUserName;
        this.initData.applyTime = data.financePayApply.applyTime;
        this.initData.applyDeptName = data.applyDeptName;
        this.approveProgressHtmlStr = data.approveProgressHtmlStr;

        //下拉框选项
        this.initData.currencyMap = data.currencyMap;
        this.initData.companyBankMap = data.companyBankMap;
        this.initData.userMap = data.userMap;
        this.initData.costNamesMap = data.costNamesMap;
        this.initData.deptMap = data.deptMap;

        //服务商（公司简称）
        this.serveCompanyMap = data.serveCompanyMap;
        this.serveCompanySelectDisabled = true;

        //收款账户
        let serveCompanyAccountList = data.serveCompanyAccountList;
        for (let account of serveCompanyAccountList) {
          let accountShowName = account.payee + '(' + account.bankAccount + ' ' + account.payBank + account.bankAddress + ')';
          account.accountShowName = accountShowName;
        }
        this.serveCompanyAccountList = serveCompanyAccountList;

        //附件
        this.fileTableData = data.files;

        this.payApplyForm = data.financePayApply;

        //汇率(JPY*RMB=1:0.07)
        this.offAccountCurrencyRate = data.offAccountCurrencyRate;
        //汇率(对应保存至数据库中的数据)
        this.selectData = data.financePayApply.financeRates;

        //销账明细
        this.tableData = data.financeReceiveDetails;
      },

      //销账金额输入框获取焦点事件
      onFocus(event, scope) {
        this.$set(scope.row, "offMoney", scope.row.remain);
        event.target.select();
      },

      //导出销账明细
      exportTableData() {
        /* 从表生成工作簿对象 */
        var wb = XLSX.utils.table_to_book(document.querySelector("#out-eltable"));
        /* 获取二进制字符串作为输出 */
        var wbout = XLSX.write(wb, {
          bookType: "xlsx",
          bookSST: true,
          type: "array"
        });
        try {
          FileSaver.saveAs(
            //Blob 对象表示一个不可变、原始数据的类文件对象。
            //Blob 表示的不一定是JavaScript原生格式的数据。
            //File 接口基于Blob，继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
            //返回一个新创建的 Blob 对象，其内容由参数中给定的数组串联组成。
            new Blob([wbout], { type: "application/octet-stream" }),
            //设置导出文件名称
            "销账明细.xlsx"
          );
        } catch (e) {
          if (typeof console !== "undefined") console.log(e, wbout);
        }
        return wbout;
      },

      /**
       * 总计
       * 统计销账金额，按不同币种计算总计金额
       * */
      async amountTotal() {
        // debugger
        this.loading = true;
        let currency = this.payApplyForm.currencyType;
        if (!currency) {
          this.$message.error("请先选择目标币种");
          this.loading = false;
          return;
        }
        //汇率(JPY*RMB=1:0.07)
        let offAccountCurrencyRate = this.offAccountCurrencyRate;
        //校验币种
        this.checkCurrency();
        let checkResult = this.checkCurrencyResult;
        if (!checkResult && offAccountCurrencyRate.length == 0) {
          this.$message.error("请先选择汇率");
          return false;
        }
        let offMap = {};
        let data = this.tableData;
        if (!(data && data.length > 0)) {
          this.$message.error("请先查询出销账明细");
          return;
        }
        //?
        data.forEach(item => {
          let _currency = item.currency;
          let offMoney = item.offMoney;
          if (
            _currency &&
            offMoney !== null &&
            offMoney !== "" &&
            offMoney !== undefined &&
            !isNaN(Number(offMoney))
          ) {
            let has = _currency in offMap;
            if (has) {
              let existVal = offMap[_currency];
              let res = Number(existVal) + Number(offMoney);
              res = Math.round(res * 100) / 100;
              offMap[_currency] = res;
            } else {
              offMap[_currency] = Number(offMoney);
            }
          }
        });
        // 获取汇率区域信息
        /* 请求示例**/
        /*
        var data = {};
        data["currency"] = "EUR";
        data["rateData"] = "";
        data["offMap"] = '{"EUR":12.43}';*/
        let res = await ajax("total", {
          currency: currency,
          rateData: JSON.stringify(this.writeoffData),
          offMap: JSON.stringify(offMap)
        });
        console.log(res);
        if (res.success == true) {
          // 总计渲染
          this.totalOffResult = res.totalOffResult;
          this.totalDataNum = res.totalDataNum;
          this.isShow = true;
          this.totalWriteOffTitle = true;
          // 渲染销账总计下面各个币种
          this.offCurrencyMap = offMap;
        } else {
          //后端有校验：包含外币时必须选择汇率
          this.$message.error(res.message);
        }
        this.loading = false;
      },

      // 校验币种,总计按钮时调用
      checkCurrency() {
        let data = this.tableData;
        if (!(data && data.length > 0)) {
          this.checkCurrencyResult = true;
          return;
        }
      },

      //销账金额，全选
      selectAll() {
        this.$nextTick(() => {
          this.texts = !this.texts;
        });
        //全选
        if (this.texts) {
          let tableData = this.tableData;
          if (!(tableData && tableData.length > 0)) {
            return;
          }
          tableData.forEach(item => {
            item.offMoney = item.remain;
          });
        } else {
          //全不选
          let tableData = this.tableData;
          if (!(tableData && tableData.length > 0)) {
            return;
          }
          tableData.forEach(item => {
            item.offMoney = "";
          });
        }
      },

      //附件上传
      fileUpload(params) {
        // debugger
        const file = params.file;
        const form = new FormData();
        // 文件对象
        form.append("items[]", file);
        axios({
          method: "post",
          url: this.action,
          data: form
        })
          .then(response => {
            debugger
            if (response.data.code === 200) {
              let files = response.data.data;
              for (let fileObj of files) {
                fileObj.fileSize = this.formatFileSize(fileObj.fileSize);
                this.fileTableData.push(fileObj);
              }
            }
          })
          .catch(error => {
            console.log(error);
            this.$notify.error({
              title: "错误",
              message: "上传失败!"
            });
          });
      },

      formatFileSize(fileSize) {
        if (fileSize < 1024 * 1024) {
          //显示成“K”
          fileSize = fileSize / 1024;
          fileSize = fileSize.toFixed(2) + "K";
        } else {
          //显示成“M”
          fileSize = fileSize / 1024 / 1024;
          fileSize = fileSize.toFixed(2) + "M";
        }
        return fileSize;
      },

      //生成手续费
      async genServiceCharge() {
        let tableData = this.tableData;
        if (tableData.length == 0) {
          this.$message.error("请先查询销账明细数据！");
          return;
        }
        let waybillId = tableData[0].waybillId;
        let serviceCharge = this.payApplyForm.serviceCharge;
        let currency = this.payApplyForm.serviceChargeCurrencyType;
        let serveCompanyId = this.payApplyForm.serveCompanyId;
        let feeBelongDeptId = this.payApplyForm.feeBelongDeptId;
        let remark = '付款申请，生成银行手续费';
        if (!serviceCharge) {
          this.$message.error("请填写手续费");
          return;
        }
        if (!currency) {
          this.$message.error("请选择手续费币种");
          return;
        }
        if (!feeBelongDeptId) {
          this.$message.error("请选择费用中心");
          return;
        }
        this.loading = true;
        const { code, data, message } = await ajax("genServiceChargeRecord", {
          serviceCharge: serviceCharge,
          currency: currency,
          waybillId: waybillId,
          serveCompanyId: serveCompanyId,
          feeBelongDeptId: feeBelongDeptId,
          remark: remark
        });
        // debugger
        if (code !== 200) {
          if (message) {
            this.$message.error(message);
          } else {
            this.$message.error("服务器异常");
          }
          this.loading = false;
          return;
        }
        //重新加载销账明细列表
        this.reloadReceiveDetails();
        //更新总计金额
        if (this.isShow) {
          this.reCalcTotal();
        }
        this.loading = false;
        this.$message({
          type: "success",
          message: "费用生成成功！"
        });
      },

      // 重新加载销账明细列表，并更新待支付余额
      // 点击“生成费用”时方法内部调用
      async reloadReceiveDetails() {
        // region 查询条件
        let data = {};
        // 服务商id
        let serCusId = this.payApplyForm.serveCompanyId;
        serCusId = 'Ser_' + serCusId;
        if (serCusId) {
          data.serCusId = serCusId;
        }
        // 录入人
        const inputUser = this.searchForm.inputUser;
        if (inputUser) {
          data.inputUser = inputUser;
        }
        // 应收应付备注
        const receivePayRemark = this.searchForm.receivePayRemark;
        if (receivePayRemark) {
          data.receivePaymentReamrk = receivePayRemark;
        }
        //费用时间
        const accountDate = this.searchForm.accountDate;
        if (accountDate && accountDate.length === 2) {
          const startAccountTime = accountDate[0];
          if (startAccountTime) {
            data.startAccountTime = startAccountTime;
          }
          const endAccountTime = accountDate[1];
          if (endAccountTime) {
            data.endAccountTime = endAccountTime;
          }
        }
        //费用类型
        data.costType = this.searchForm.costType;

        //销售
        const salesManId = this.searchForm.salesManId;
        if (salesManId) {
          data.saleId = salesManId;
        }
        // 费用名称
        const costNames = this.searchForm.costNames;
        if (costNames) {
          data.costNames = costNames;
        }

        // 费用币种
        const filterCurrency = this.searchForm.currency;
        if (filterCurrency) {
          data.filterCurrency = filterCurrency;
        }
        //运单号
        const waybillNos = this.searchForm.waybillNos;
        if (waybillNos) {
          data.waybillNos = waybillNos.split("\n");
        }
        //参考号
        const referenceNos = this.searchForm.referenceNos;
        if (referenceNos) {
          data.referenceNos = referenceNos.split("\n");
        }
        //M单号
        const masterNumbers = this.searchForm.masterNumbers;
        if (masterNumbers) {
          data.masterNumbers = masterNumbers.split("\n");
        }
        //追踪号
        const trackNumbers = this.searchForm.trackNumbers;
        if (trackNumbers) {
          data.trackNumbers = trackNumbers.split("\n");
        }
        //endregion
        let res = await ajax("queryFinanceReceiveDetails", data);
        this.tableData = res.data.tableData;
        // debugger;
        //给“待支付余额”赋值
        let tableData = this.tableData;
        console.log("重新加载销账明细列表成功！");
        let totalRemain = 0;
        tableData.forEach(item => {
          totalRemain += item.remain;
        });
        this.payApplyForm.toPayAmt = totalRemain;
        console.log("更新待支付余额成功！");
      },

      // 更新总计金额
      // 点击“生成费用”时方法内部调用
      async reCalcTotal() {
        let currency = this.payApplyForm.currencyType;
        if (!currency) {
          console.log("error:点击生成费用时更新总计金额，请先选择目标币种！");
          this.loading = false;
          return;
        }
        //汇率(JPY*RMB=1:0.07)
        let offAccountCurrencyRate = this.offAccountCurrencyRate;
        //校验币种
        this.checkCurrency();
        let checkResult = this.checkCurrencyResult;
        if (!checkResult && offAccountCurrencyRate.length == 0) {
          this.$message.error("请先选择汇率");
          return false;
        }
        let offMap = {};
        let data = this.tableData;
        if (!(data && data.length > 0)) {
          return;
        }
        data.forEach(item => {
          let _currency = item.currency;
          let offMoney = item.offMoney;
          if (
            _currency &&
            offMoney !== null &&
            offMoney !== "" &&
            offMoney !== undefined &&
            !isNaN(Number(offMoney))
          ) {
            let has = _currency in offMap;
            if (has) {
              let existVal = offMap[_currency];
              let res = Number(existVal) + Number(offMoney);
              res = Math.round(res * 100) / 100;
              offMap[_currency] = res;
            } else {
              offMap[_currency] = Number(offMoney);
            }
          }
        });
        // 获取汇率区域信息
        /* 请求示例**/
        /*
        var data = {};
        data["currency"] = "EUR";
        data["rateData"] = "";
        data["offMap"] = '{"EUR":12.43}';*/
        let res = await ajax("total", {
          currency: currency,
          rateData: JSON.stringify(this.writeoffData),
          offMap: JSON.stringify(offMap)
        });
        if (res.success == true) {
          // 总计渲染
          this.totalOffResult = res.totalOffResult;
          this.totalDataNum = res.totalDataNum;
          this.isShow = true;
          this.totalWriteOffTitle = true;
          // 渲染销账总计下面各个币种
          this.offCurrencyMap = offMap;
          console.log("更新总计金额成功！");
        } else {
          //后端有校验：包含外币时必须选择汇率
          this.$message.error(res.message);
        }
      },

      //生成电讯费
      async genTelecomCharge() {
        let tableData = this.tableData;
        if (tableData.length == 0) {
          this.$message.error("请先查询销账明细数据！");
          return;
        }
        let waybillId = tableData[0].waybillId;
        let telecomCharge = this.payApplyForm.telecomCharge;
        let currency = this.payApplyForm.telecomChargeCurrencyType;
        let serveCompanyId = this.payApplyForm.serveCompanyId;
        let feeBelongDeptId = this.payApplyForm.feeBelongDeptId;
        let remark = '付款申请，生成银行手续费(电讯费)';
        if (!telecomCharge) {
          this.$message.error("请填写电讯费");
          return;
        }
        if (!currency) {
          this.$message.error("请选择电讯费币种");
          return;
        }
        if (!feeBelongDeptId) {
          this.$message.error("请选择费用中心");
          return;
        }
        this.loading = true;
        const { code, data, message } = await ajax("genServiceChargeRecord", {
          serviceCharge: telecomCharge,
          currency: currency,
          waybillId: waybillId,
          serveCompanyId: serveCompanyId,
          feeBelongDeptId: feeBelongDeptId,
          remark: remark
        });
        // debugger
        if (code !== 200) {
          if (message) {
            this.$message.error(message);
          } else {
            this.$message.error("服务器异常");
          }
          this.loading = false;
          return;
        }
        //重新加载销账明细列表
        this.reloadReceiveDetails();
        //更新总计金额
        if (this.isShow) {
          this.reCalcTotal();
        }
        this.loading = false;
        this.$message({
          type: "success",
          message: "费用生成成功！"
        });
      },

      showInput() {
        this.showRate = false;
        this.showInputRate = true;
      },

      //校验必填
      submitForm(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            this.commit();
          } else {
            console.log("数据校验失败，不允许提交");
            return false;
          }
        });
      },

      //查询服务商
      async searchServeCompany(query) {
        if (query !== "" && query.length > 1) {
          let res = await ajax("searchServeCompany", {
            arg: query
          });
          this.serveCompanyMap = res;
        }
      },

      //查询初始化数据
      async init() {
        const { code, data, message } = await ajax("getInitData", {});
        if (code !== 200) {
          if (message) {
            this.$message.error(message);
          } else {
            this.$message.error("服务器异常");
          }
          return;
        }
        this.initData = data;
        //基本信息保存至payApplyForm
        this.payApplyForm.applyNo = this.initData.applyNo;
        this.payApplyForm.applyUserId = this.initData.applyUserId;
        this.payApplyForm.applyTime = this.initData.applyTime;
        this.payApplyForm.applyDeptId = this.initData.applyDeptId;
      },

      //查询所有汇率
      async selectRate() {
        let targetCurrency = this.payApplyForm.currencyType;
        if (!targetCurrency) {
          this.$message.error("请选择记账币种!");
          return;
        }
        let res = await ajax("selectOffAccountCurrencyRate", {
          arg: targetCurrency
        });
        this.writeoffData = res.offAccountCurrencyRates;
        this.dialogTableVisible = true;
      },

      //保存汇率
      async saveRate() {
        this.selectData = this.$refs.accountTable.selection;
        if (!this.selectData) {
          this.$message.error("请选择记账汇率!");
          return;
        }
        let array = new Array();
        let checkArray = new Array();
        //选择的汇率
        let sourceCurrencyArray = new Array();
        let flag = false;
        for (let i = 0; i < this.selectData.length; i++) {
          let selectedRow = this.selectData[i];
          let sourceCurrency = selectedRow.sourceCurrency;
          let targetCurrency = selectedRow.targetCurrency;
          let rate = selectedRow.rate;
          let operator = selectedRow.operator;
          let checkPa = sourceCurrency + targetCurrency;
          //校验
          if (checkArray.includes(checkPa)) {
            flag = true;
            return false;
          } else {
            checkArray.push(checkPa);
          }
          array.push({
            sourceCurrency: sourceCurrency,
            targetCurrency: targetCurrency,
            rate: rate,
            operator: operator
          });
          if (!sourceCurrencyArray.includes(sourceCurrency)) {
            sourceCurrencyArray.push(sourceCurrency);
          }
        }
        if (array.length == 0) {
          this.$message.error("请先选择销账汇率");
          return;
        }
        let selectTargetCurrency = this.payApplyForm.currencyType;
        //销账明细中的币种
        let offCurrencyArray = new Array();
        if (this.tableData) {
          this.tableData.forEach(item => {
            let offMoney = item.offMoney;
            let currency = item.currency;
            if (
              offMoney &&
              !isNaN(Number(offMoney)) &&
              currency &&
              currency != selectTargetCurrency &&
              !offCurrencyArray.includes(currency)
            ) {
              offCurrencyArray.push(currency);
            }
          });
          offCurrencyArray.forEach(item => {
            if (!sourceCurrencyArray.includes(item)) {
              flag = true;
              return false;
            }
          });
          if (flag) {
            this.$message.error("请先选择要销账币种的销账汇率", "", 1000);
            return;
          }
        }

        let res = await ajax("saveSelectOffAccountCurrencyRate", {
          data: JSON.stringify(array)
        });
        this.writeoffData = this.selectData;
        if (res.success) {
          this.offAccountCurrencyRate = res.result;//后端处理成这种格式：USD*RMB=1:6.95
          this.dialogTableVisible = false;
        } else {
          this.$message.error("请先选择销账汇率！");
        }
      },

      /**
       * 保存
       * 不进行任何校验，直接保存。
       * 给“总销账金额”赋值。
       * */
      async save() {
        let applyId = this.payApplyForm.id;
        //汇率
        this.payApplyForm.financeRates = this.selectData;
        let financeRates = this.selectData;
        let financeRateMap = new Map();
        financeRates.forEach(item => {
          financeRateMap.set(item.sourceCurrency, item.rate);
        });

        //计算总销账金额(申请金额+手续费+电讯费)
        let applyAmt = this.payApplyForm.applyAmt;
        let applyAmtCurrency = this.payApplyForm.currencyType;
        let serviceCharge = this.payApplyForm.serviceCharge;
        let serviceChargeCurrency = this.payApplyForm.serviceChargeCurrencyType;
        let telecomCharge = this.payApplyForm.telecomCharge;
        let telecomChargeCurrency = this.payApplyForm.telecomChargeCurrencyType;
        if (!serviceCharge && serviceCharge !== 0) {
          serviceCharge = 0;
        }
        if (!telecomCharge && telecomCharge !== 0) {
          telecomCharge = 0;
        }
        if (applyAmtCurrency && applyAmtCurrency != 'RMB' && financeRateMap.get(applyAmtCurrency) == null) {
          let errorMsg = '请选择' + applyAmtCurrency + '的汇率！';
          this.$message.error(errorMsg);
          return;
        }
        if (serviceChargeCurrency && serviceChargeCurrency != 'RMB' && financeRateMap.get(serviceChargeCurrency) == null) {
          let errorMsg = '请选择' + serviceChargeCurrency + '的汇率！';
          this.$message.error(errorMsg);
          return;
        }
        if (telecomChargeCurrency && telecomChargeCurrency != 'RMB' && financeRateMap.get(telecomChargeCurrency) == null) {
          let errorMsg = '请选择' + telecomChargeCurrency + '的汇率！';
          this.$message.error(errorMsg);
          return;
        }
        //币种为外币时，需转换为RMB，再参与计算
        if (applyAmt !== 0 && applyAmtCurrency != 'RMB') {
          let rate = financeRateMap.get(applyAmtCurrency);
          applyAmt = applyAmt * rate;
        }
        if (serviceCharge !== 0 && serviceChargeCurrency != 'RMB') {
          let rate = financeRateMap.get(serviceChargeCurrency);
          serviceCharge = serviceCharge * rate;
        }
        if (telecomCharge !== 0 && telecomChargeCurrency != 'RMB') {
          let rate = financeRateMap.get(telecomChargeCurrency);
          telecomCharge = telecomCharge * rate;
        }
        this.payApplyForm.totalOffAmount = applyAmt + serviceCharge + telecomCharge;

        //销账明细
        let tableData = this.tableData;
        let payments = [];
        //应付
        for (const item of tableData) {
          if (item.offMoney == null) {
            this.$message.error("请填写销账金额！");
            return;
          }
          let payment = {};
          payment.paymentId = item.waybillReceivePayablesId;
          payment.offMoney = item.offMoney;
          payment.isAbroad= item.isAbroad;
          payment.financePayApplyId = applyId;
          payment.waybillId = item.waybillId;
          payment.costNameId = item.costNameId;
          payments.push(payment);
        }
        this.payApplyForm.payApplyPayments = payments;
        //附件
        let fileTableData = this.fileTableData;
        for (const item of fileTableData) {
          item.applyId = applyId;
        }

        const { code, data, message } = await ajax("save", {
          payApply: this.payApplyForm,
          files: fileTableData
        });
        if (code !== 200) {
          if (message) {
            this.$message.error(message);
          } else {
            this.$message.error("服务器异常");
          }
          return;
        }
        //新增成功，后台返回payApplyId
        if (!applyId) {
          this.payApplyForm.id = data;
        }
        this.$message({
          type: "success",
          message: "保存成功！"
        });
      },

      //提交付款申请
      async commit() {
        let payApplyId = this.payApplyForm.id;
        if (!payApplyId) {
          this.$message.error("请先保存！");
          return;
        }
        //校验：附件不能为空
        if (this.fileTableData.length === 0) {
          this.$message.error("请上传附件");
          return;
        }
        //校验：总销账金额必须等于总计金额
        let totalOffAmount = this.payApplyForm.totalOffAmount;
        let totalDataNum = this.totalDataNum;
        if (totalOffAmount != totalDataNum) {
          this.$message.error("总销账金额必须等于总计金额");
          return;
        }
        let ids = [];
        ids.push(payApplyId);
        const { code, data, message } = await ajax("commit", {
          ids: ids
        });
        if (code !== 200) {
          if (message) {
            this.$message.error(message);
          } else {
            this.$message.error("服务器异常");
          }
          return;
        }
        this.$message({
          type: "success",
          message: "提交成功！"
        });
        window.location.href = '/#/main/finance__payapply__list';
      },

      //查询服务商收款账户（根据公司简称带出）
      async queryServeCompanyAccount() {
        let serverId = this.payApplyForm.serveCompanyId;
        if(!serverId){
          return;
        }
        // debugger;
        const { code, data, message } = await ajax("queryServeCompanyAccount", {
          serverId: serverId
        });
        if (code !== 200) {
          if (message) {
            this.$message.error(message);
          } else {
            this.$message.error("服务器异常");
          }
          return;
        }
        let list = data;
        for(let account of list){
          let accountShowName = account.payee+'('+account.bankAccount+' '+account.payBank+account.bankAddress+')';
          account.accountShowName = accountShowName;
        }
        this.serveCompanyAccountList = list;
      },

      //查询销账明细列表数据
      async queryFinanceReceiveDetails() {
        this.loading = true;
        if (this.$route.query.pid !== undefined) {
          this.receiveItemDialogVisible = true;
        }
        //region 查询条件
        let data = {};
        // 服务商id
        let serCusId = this.payApplyForm.serveCompanyId;
        serCusId = 'Ser_' + serCusId;
        if (serCusId) {
          data.serCusId = serCusId;
        }
        // 录入人
        const inputUser = this.searchForm.inputUser;
        if (inputUser) {
          data.inputUser = inputUser;
        }
        // 应收应付备注
        const receivePayRemark = this.searchForm.receivePayRemark;
        if (receivePayRemark) {
          data.receivePaymentReamrk = receivePayRemark;
        }
        //费用时间
        const accountDate = this.searchForm.accountDate;
        if (accountDate && accountDate.length === 2) {
          const startAccountTime = accountDate[0];
          if (startAccountTime) {
            data.startAccountTime = startAccountTime;
          }
          const endAccountTime = accountDate[1];
          if (endAccountTime) {
            data.endAccountTime = endAccountTime;
          }
        }
        //费用类型
        data.costType = this.searchForm.costType;
        //销售
        const salesManId = this.searchForm.salesManId;
        if (salesManId) {
          data.saleId = salesManId;
        }
        // 费用名称
        const costNames = this.searchForm.costNames;
        if (costNames) {
          data.costNames = costNames;
        }

        // 费用币种
        const filterCurrency = this.searchForm.currency;
        if (filterCurrency) {
          data.filterCurrency = filterCurrency;
        }
        //运单号
        const waybillNos = this.searchForm.waybillNos;
        if (waybillNos) {
          data.waybillNos = waybillNos.split("\n");
        }
        //参考号
        const referenceNos = this.searchForm.referenceNos;
        if (referenceNos) {
          data.referenceNos = referenceNos.split("\n");
        }
        //M单号
        const masterNumbers = this.searchForm.masterNumbers;
        if (masterNumbers) {
          data.masterNumbers = masterNumbers.split("\n");
        }
        //追踪号
        const trackNumbers = this.searchForm.trackNumbers;
        if (trackNumbers) {
          data.trackNumbers = trackNumbers.split("\n");
        }
        //endregion
        let res = await ajax("queryFinanceReceiveDetails", data);
        this.tableData = res.data.tableData;
        //给“待支付余额”赋值
        let tableData = this.tableData;
        let totalRemain = 0;
        tableData.forEach(item => {
          totalRemain += item.remain;
        });
        this.payApplyForm.toPayAmt = totalRemain;
        this.costNamesMap = res.data.costNamesMap;
        this.loading = false;
      },

      //附件下载
      fileDownload(index, row) {
        let filePath = row.filePath;//  "/data/upload/tmp/upload/测试上传附件20211112b28.xlsx"
        let fileName = encodeURIComponent(row.fileName);// 测试上传附件20211112b28.xlsx
        let server = constant.FILE_SERVER;
        let fileUrl = server + filePath;
        location.href = constant.API_SERVER + "/open/downloadFileByHttp?path=" + fileUrl + "&fileName=" + fileName;
      }
    }
  };
</script>


<style>
  .my_color {
    color: #ff7575;
    cursor: pointer;
  }
  .my_left {
    margin-left: 54px;
  }

</style>
